/**
 * Copyright 1996 self.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 *
 * @author Ashin Wimalajeewa
 *
 * Note, this is a very old runtime library that I have evolved since 1996. I rarely use it
 * now because the Apache Commons project has made it obsolete.
 */
package self.oss.svn.client;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import self.text.ReplacementUtils;

public class MergeInDirection {
	final static public String DEFAULT_SVN_FOLDERS = ".svn";
	final static public String MERGE_LEFT_SIG = ".merge-left.r";
	final static public String MERGE_RIGHT_SIG = ".merge-right.r";
	final static public String MERGE_LEFT_PATTERN = ".*\\.merge-left\\.r\\d+";
	final static public String MERGE_LEFT_PATTERN_SUFFIX = "\\.merge-left\\.r\\d+";
	final static public String MERGE_RIGHT_PATTERN_SUFFIX = "\\.merge-right\\.r\\d+";
	
	private String svnFolderName = DEFAULT_SVN_FOLDERS;
	private boolean mergeRight;
	private boolean mergeHighest;
	
	public MergeInDirection(String svnFldrs, boolean right, boolean highest) {
		if (svnFldrs != null)
			svnFolderName = svnFldrs;
		mergeRight = right;
		mergeHighest = highest;
	}
	
	public void run() throws Exception {
		String currFolderAsStr = System.getProperty("user.dir");
		File currFolder = new File(currFolderAsStr);
		mergeDirectoryContents(currFolder);
	}
	
	private void mergeDirectoryContents(File dir) throws Exception {
		File[] contents = dir.listFiles();
		StringBuffer buff = new StringBuffer("\r\n");
		for (int i = 0; i < contents.length; i++) {
			String name = contents[i].getName();
			boolean isFolder = contents[i].isDirectory();
			if (isFolder & name.equals(svnFolderName))
				continue;
			if (isFolder)
				mergeDirectoryContents(contents[i]);
			else {
				String abs = contents[i].getAbsolutePath();
				buff.append(abs).append("\r\n");
			}
		}
		manageMerge(buff.toString());
	}
	
	private void manageMerge(String dirList) throws Exception {
		List candidates = identifyCandidates(dirList);
		resolveCandidates(dirList, candidates);
	}
	
	private void resolveCandidates(String dirList, List candidates) throws Exception {
		for (Iterator iter = candidates.iterator(); iter.hasNext();) {
			String candidate = (String) iter.next();
			File candFile = new File(candidate);
			if (candFile.exists())
				resolveMerge(dirList, candidate);
		}
	}
	
	private void resolveMerge(String dirList, String candidate) throws Exception {
		String encCandidate = ReplacementUtils.encodeForRegex(candidate);
		String keepPat = encCandidate + (mergeRight ? MERGE_RIGHT_PATTERN_SUFFIX: MERGE_LEFT_PATTERN_SUFFIX); 
		String delPat = encCandidate + (mergeRight ? MERGE_LEFT_PATTERN_SUFFIX: MERGE_RIGHT_PATTERN_SUFFIX);
		deleteUnwantedRevisions(dirList, delPat);
		renameDesiredRevision(dirList, candidate, keepPat);
		deleteUnwantedRevisions(dirList, keepPat);
	}
	
	private void renameDesiredRevision(String dirList, String candidate, String keepPat) throws Exception {
		Pattern mergeLeftPattern = Pattern.compile(keepPat);
		Matcher m = mergeLeftPattern.matcher(dirList);
		ArrayList subCandidates = new ArrayList();
		while (m.find()) {
			String entry = m.group(0);
			subCandidates.add(entry);
		}
		Comparator cmp = new RevisionComparator(!mergeHighest);
		Collections.sort(subCandidates, cmp);
		String keepFile = (String) subCandidates.get(0);
		File candAsFile = new File(candidate);
		System.out.println("Deleting: " + candidate);
		candAsFile.delete();
		File keepAsFile = new File(keepFile);
		System.out.println("Renaming: " + keepFile + " to " + candidate);
		keepAsFile.renameTo(candAsFile);
	}
	
	private void deleteUnwantedRevisions(String dirList, String delPat) throws Exception {
		Pattern mergeLeftPattern = Pattern.compile(delPat);
		Matcher m = mergeLeftPattern.matcher(dirList);
		while (m.find()) {
			String entry = m.group(0);
			File toDel = new File(entry);
			System.out.println("Deleting: " + toDel);
			toDel.delete();
		}		
	}

	private List identifyCandidates(String dirList) {
		ArrayList candidates = new ArrayList();
		Pattern mergeLeftPattern = Pattern.compile(MERGE_LEFT_PATTERN);
		Matcher m = mergeLeftPattern.matcher(dirList);
		while (m.find()) {
			String match = m.group(0);
			int pos = match.indexOf(MERGE_LEFT_SIG);
			String entry = match.substring(0, pos);
			if (!candidates.contains(entry))
				candidates.add(entry);
		}
		return candidates;
	}
	
	static private class RevisionComparator implements Comparator {
		private boolean lowestFirst;
		
		public RevisionComparator(boolean lf) {
			lowestFirst = lf;
		}
		
		public int compare(Object arg0, Object arg1) {
			String arg0AsStr = (String) arg0;
			String arg1AsStr = (String) arg1;
			int ret = arg0AsStr.compareTo(arg1AsStr);
			if (lowestFirst)
				return ret;
			return -ret;
		}
	}
}
